<?
	require_once "../../commons/includes/stringutils.inc";
	
	function quoteValue($originalValue,$dataType){
		
		if($dataType=="text" || $dataType=="fulltext"){
			if("$originalValue"=="") $value="null";
			else {
				$value = stripslashes($originalValue);
				$value = "'".  str_replace("'","''",$value ) ."'";
			}	
		}else if($dataType=="DateTime" || $dataType=="datetime"){
			if("$originalValue"=="") $value="null";
			else {
				$value = StringUtils::dateStringToString ($originalValue);
				$value = "'" . $value . "'";
			}	
		}else if($dataType=="ID"){
			if("$originalValue"=="") $value="0";
			else $value = $originalValue;
		}else{
			if("$originalValue"=="") $value=0;
			else $value = $originalValue;
		}	
		return $value;
	}
	
	function createSqlInsert($table,&$values){
		$dbdef = &$GLOBALS['dbdef'];
	
		$tabledef = &$dbdef [$table];
		$count = 0;
		
		foreach($tabledef as $key=>$fieldDef ){
			$dataType = $fieldDef ['DataType']; 

			if($dataType!="ID") {
				unset($value);
				$value = quoteValue($values[$key],$dataType);
				
				if($count>0){
					$fieldsForSql.=", \n $key";
					$valuesForSql.=", \n $value";
				}else{
					$fieldsForSql.=" \n $key";
					$valuesForSql.=" \n $value";
				}
				
				$count++;
			}
			
		}
		
		return "INSERT INTO $table ($fieldsForSql\n)VALUES(\n$valuesForSql)" ;
	}
	
	function createSqlUpdate($table,&$values,$where=''){
		$dbdef = &$GLOBALS['dbdef'];
	
		$tabledef = &$dbdef [$table];
		$count = 0;
		
		foreach($tabledef as $key=>$fieldDef ){
			
			$dataType = $fieldDef ['DataType']; 
			
			unset($value);	
			if($dataType!="ID") {
				if (isset($values[$key])) {
					$value = quoteValue($values[$key],$dataType);
				
					if($count>0){
						$valuesForSql.=", \n $key=$value";
					}else{
						$valuesForSql.=" \n $key=$value";
					}
					
					$count++;
				}
			}else {//$dataType=="ID"
				$value = quoteValue($values["O_$key"],$dataType);	
				$where = "WHERE $key=" . $value ; 
			}
			
		}
		if (empty($where)) {
		    exit("missing condition");
		}
		return "UPDATE $table SET $valuesForSql $where" ;
	}
?>